package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    //新增分类
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加成功");
    }

    //分页查询
    @GetMapping("/page")
    public R<Map> page(int page, int pageSize) {
        //分页构造器
        Page<Category> pg = new Page(page, pageSize);
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.orderByAsc(Category::getSort);
        categoryService.page(pg, qw);
        List<Category> records = pg.getRecords();
        long total = pg.getTotal();
        HashMap<String, Object> map = new HashMap();
        map.put("records", records);
        map.put("total", total);
        return R.success(map);
    }

    //删除分类
    @DeleteMapping
    public R<String> delete(Long id) {
        categoryService.removeById(id);
        return R.success("删除成功");
    }

    //修改分类
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    //菜品分类查询
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        //1.条件构造器
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        //2.添加分类条件
        qw.eq(category.getType() != null, Category::getType, category.getType());
        //3.排序
        qw.orderByDesc(Category::getSort);
        List<Category> list = categoryService.list(qw);
        return R.success(list);
    }
}
